package com.itheima.controller;


import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.RedisConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import com.itheima.utils.QiniuUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.io.IOException;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/setmeal")
public class SetmealController {

    @Reference
    SetmealService setmealService;

    @Autowired
    JedisPool jedisPool;

    @RequestMapping("/upload")
    public Result upload(@RequestParam("imgFile")MultipartFile imgFile){
        try {
        //获取原始的文件名
        String originalFilename = imgFile.getOriginalFilename();
        int lastindexof = originalFilename.lastIndexOf(".");

        String suffix = originalFilename.substring(lastindexof);
        String fileName = UUID.randomUUID().toString() + suffix;
           QiniuUtil.upload(imgFile.getBytes(),fileName);
            Jedis resource = jedisPool.getResource();
            resource.sadd(RedisConstant.SETMEAL_PIC_RESOURCES,fileName);
            resource.close();
            //图片上传成功
            return  Result.success("",fileName);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("");
        }

    }

    @RequestMapping("/add")
    public Result add(@RequestBody Setmeal setmeal){
         setmealService.add(setmeal);
        Jedis resource = jedisPool.getResource();
        resource.sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,setmeal.getImg());
        resource.close();
         return  Result.success("");
    }


    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){
       PageResult  pageResult= setmealService.findPage(queryPageBean);
        return pageResult;
    }



}
